/*
#Copyright (c) 2013, Philippe Bordron <philippe.bordron@gmail.com>
#
# This file is part of SIPPER.
#
# DCC is free software: you can redistribute it and/or modify
# it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DCC is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU LESSER GENERAL PUBLIC LICENSE for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# along with SIPPER.  If not, see <http://www.gnu.org/licenses/>
*/
package combi.wip.sipper.exec;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import combi.sipper.io.IOAssociation;
import combi.sipper.io.IOList;
import combi.sipper.io.InFlatFile;

public class ExtractOperonsFromRegulonDB {

	public static void main(String[] args) throws IOException {
		String components = "COMPONENTS";
		String name = "COMMON-NAME";
		
		Map<String, Map<String, Collection<String>>> tu = new HashMap<String, Map<String, Collection<String>>>();
		InFlatFile ioTU = new InFlatFile(args[0]);
		tu = ioTU.readFile();
		//System.out.println(tu);

		IOList ioRegulonDBNames = new IOList(args[1]);
		Set<String> regulonBDName = new HashSet<String>(ioRegulonDBNames.read());

		Collection<String>  metabolicGeneList = IOAssociation.loadInteger(args[2], "(?:(\\S+)\\s+(.+))").keySet();
		//System.out.println(metabolicGeneList);
		for (Entry<String, Map<String, Collection<String>>> entry : tu.entrySet())
		{
			Collection<String> commonNamesCollection = entry.getValue().get(name);	
			Set<String> commonNames = new HashSet<String>();
			if (commonNamesCollection != null)
			{
				commonNames.addAll(commonNamesCollection);
			}
			commonNames.retainAll(regulonBDName);
			if(!commonNames.isEmpty())
			{
				Collection<String> genes = entry.getValue().get(components);
				if (genes != null)
				{
					genes.retainAll(metabolicGeneList);
					if (genes.size()>1)
					{
						System.out.println(entry.getKey() + "\t" +collectionToString(genes));
					}
				}
			}
		}
	}

	private static String collectionToString (Collection<String> c)
	{
		return c.toString().replaceAll("[\\[,\\]]", "");
	}
}
